package org.example.controller;

import org.example.entity.User;
import org.example.service.JobPostService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Date;

@RestController
@RequestMapping("/api/jobs")
public class JobController {

    private final JobPostService jobPostService;
    private final UserService userService;

    @Autowired
    public JobController(JobPostService jobPostService, UserService userService) {
        this.jobPostService = jobPostService;
        this.userService = userService;
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getJobDetails(@PathVariable Long id, @RequestParam Long userId) {
        User user = userService.getUser(userId);
        checkViewLimit(user);
        return ResponseEntity.ok().build();
    }

    private void checkViewLimit(User user) {
        if (!user.isMember()) {
            LocalDate currentDate = LocalDate.now();
            Date utilDate = java.sql.Date.valueOf(currentDate);
            if (!utilDate.equals(user.getLastActionDate())) {
                user.setDailyViewCount(0);
                user.setLastActionDate(utilDate);
            }

            if (user.getDailyViewCount() >= 10) {
                throw new RuntimeException("查看次数已达上限");
            }

            user.setDailyViewCount(user.getDailyViewCount() + 1);
            userService.save(user);
        }
    }
}
